// pages/okOrder/okOrder.js
var app = getApp()
import {
  getCart,
  getUserPrefer,
  postOrderCreate,
  getUserOrderInfo,
  postPay,
  postOrderUpdate,
  getRestaurantAddress,
  getUserBalance,
  posPrintMsg,
  postPayJuhe
} from '../../api/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    showPay: false, //支付方式
    showCoupun: false, //优惠卷
    cartData: {
      type: 1, //支付方式
      yhprice: 0, //优惠金额
      bz: '', //备注
      preferid: ''
    }, //购物车数据
    addressData: {}, //收货地址数据
    order_pro: [], //商品数据
    coupunId: -1, //优惠卷id
    zprice: 0, //除去配送费的价格
    totalPS: 0,
    id: -1, //订单id,
    showTextArea: true,     //备注输入框是否显示
    balance: '',    //用户余额
    payJumpShow:false
  },
  //选项支付方式显示
  onOkPayShow: function () {
    if(this.data.payJumpShow){
      getUserBalance().then(res => {
        if (res.state == 0) {
          this.setData({
            balance: res.data.balance
          })
        }
      })
      this.setData({
        showPay: !this.data.showPay,
        showTextArea: !this.data.showTextArea
      })
    }
  },
  //选择支付方式
  bindPay: function (e) {
    // console.log(e)
    if(this.data.payJumpShow){
      var cartData = this.data.cartData
      cartData.type = e.currentTarget.dataset.type
      this.setData({
        cartData: cartData,
        showPay: !this.data.showPay,
        showTextArea: !this.data.showTextArea
      })
    }
    
  },
  //优惠卷显示
  coupunShow() {
    if(this.data.payJumpShow){
      this.setData({
        showCoupun: !this.data.showCoupun,
        showTextArea: !this.data.showTextArea
      })
    }
  },
  //优惠卷弹窗列表
  onCoupunShow() {
    var cartData = this.data.cartData;
    cartData.preferid = ''
    cartData.yhprice = 0
    cartData.price = this.data.totalPS
    this.setData({
      cartData: cartData,
      showCoupun: !this.data.showCoupun,
      showTextArea: !this.data.showTextArea
    })
  },
  //继续框
  jumpOrder() {
    wx.redirectTo({
      url: '../orderNew/orderNew',
    })
  },
  //点击地址   选择地址
  onAddress() {
    if(this.data.payJumpShow){
      var that = this
      wx.navigateTo({
        url: '../addressList/addressList?type=order',
        events: {
          //为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          address: function (data) {
            //这里是获取被打开页面传送到当前页面的数据
            var addressData = that.data.addressData
            addressData.street = data.street //详细地址
            addressData.address = data.address //门牌号
            addressData.name = data.name //姓名
            addressData.mobile = data.mobile
            that.setData({
              addressData: addressData
            })
            console.log('address++++', data)
          },
        },
        success: function (res) {
          //通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('orderType', {
            order: true
          })
        }
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getRestaurantAddress().then(res => { //配送条件
      if (res.state == 0) {
        if (res.data.type == 1) { //订单金额
          res.data.peisong = res.data.peisong + '元'
        } else {
          res.data.peisong = res.data.peisong + '份'
        }
        this.setData({
          peisong: res.data.peisong
        })
      }
    })
    if (options.id == undefined) {
      this.data.id = -1
      //创建订单的时候
      getCart().then(res => {
        if (res.state == 0) {
          var cart = res.data.cart
          var total = 0;
          // 显示确认支付
          this.setData({
            payJumpShow:true
          })
          //计算实付价格
          for (var i = 0; i < cart.length; i++) {
            total = total + parseFloat(cart[i].num) * parseFloat(cart[i].price);
          }
          console.error("补算配送费的价格", total)
          this.data.zprice = total; //不算配送费的
          this.getDataCoupun(total)
          total = total + parseFloat(res.data.psprice); //实付+配送费
          this.data.totalPS = total; //加上配送费的
          // console.log("实付价格", total)
          res.data.price = total.toFixed(2)
          res.data.type = 1 //支付方式
          res.data.yhprice = 0 //优惠价格
          res.data.bz = '' //备注
          res.data.preferid = '' //优惠卷id
          var addressData = {}
          if (res.data.address) {
            addressData = res.data.address
          }
          this.setData({
            cartData: res.data,
            addressData: addressData, //收货地址数据
            order_pro: res.data.cart, //商品数据
          })
        }
      })
    } else {
      this.data.id = options.id;
      getUserOrderInfo(this.data.id).then(res => {
        if (res.state == 0) {
          console.log(res.data)
          // 不是未支付的时候 就不显示 确认支付   
          if(res.data.state!=1){
            this.setData({
              payJumpShow:false
            })
            wx.setNavigationBarTitle({
              title:'订单详情'
            })
          }else{
            this.setData({
              payJumpShow:true
            })
          }
          let addressData = {
            street: res.data.street, //详细地址
            address: res.data.address, //门牌号
            name: res.data.username, //姓名
            mobile: res.data.mobile
          }
          if (res.data.bz == "null" || res.data.bz == null) {
            res.data.bz = ''
          }
          if (res.data.preferid == "null" || res.data.preferid == null) {
            res.data.preferid = ''
          }
          res.data.total = res.data.price
          var totalPS = parseFloat(res.data.price) + parseFloat(res.data.yhprice); //加上配送费的
          this.data.totalPS = totalPS.toFixed(2)
          this.data.zprice = totalPS - parseFloat(res.data.psprice) //减去配送费  商品价格
          this.getDataCoupun(totalPS)
          this.setData({
            order_pro: res.data.order_pro, //商品列表
            cartData: res.data, //数据
            addressData: addressData //收货地址
          })
        }
      })
    }

  },
  //优惠卷列表  
  getDataCoupun(total) {
    var money = total
    console.log("优惠卷+++++++", total)
    getUserPrefer().then(res => {
      if (res.state == 0) {
        var weiGuo = res.data.weiGuo;
        var coupunList = res.data.weiGuo
        for (var i = 0; i < weiGuo.length; i++) {
          if (weiGuo[i].price > money) {
            coupunList.splice(i, 1)
          }
        }
        this.setData({
          coupunList: coupunList
        })
      }
    })
  },
  //优惠卷 点击使用
  bindOkCoupun(e) {
    console.log("配送费的金额", this.data.totalPS)
    // console.log("不算配送费的",this.data.zprice)
    var data = e.currentTarget.dataset //获取点击事件的值
    if (data.type == 1) { //满减
      var cartData = this.data.cartData;
      cartData.price = this.data.totalPS - parseFloat(data.jian)
      // console.log(this.data.totalPS-parseFloat(data.jian))
      var youhui = this.data.totalPS - cartData.price;
      cartData.yhprice = youhui.toFixed(2) //优惠金额
      cartData.preferid = data.preferid //优惠卷id
      console.log(data.preferid)
      cartData.price = cartData.price.toFixed(2) //价格
      this.setData({
        cartData: cartData,
        showCoupun: !this.data.showCoupun,
        showTextArea: !this.data.showTextArea
      })
    } else { //折扣
      var cartData = this.data.cartData;
      cartData.price = this.data.totalPS * (parseFloat(data.zhekou) / 10)
      var youhui = this.data.totalPS - cartData.price;
      cartData.yhprice = youhui.toFixed(2) //优惠金额
      cartData.preferid = data.preferid //优惠卷id
      cartData.price = cartData.price.toFixed(2)
      this.setData({
        cartData: cartData,
        showCoupun: !this.data.showCoupun,
        showTextArea: !this.data.showTextArea
      })
    }
    // console.log(data)
  },
  ///备注
  bindTextArea(e) {
    var cartData = this.data.cartData
    // console.log(e.detail)
    cartData.bz = e.detail.value
    // console.log(cartData)
    this.setData({
      cartData: cartData
    })
  },
  ///提交支付
  onSubmitPay() {
    var cartData = this.data.cartData //列表
    var addressData = this.data.addressData
    console.log(addressData)
    if (addressData.street != undefined && addressData.street != '') { //判读有没有收获地址
      let data = {
        preferid: cartData.preferid, //优惠卷id
        price: cartData.price, //实付价格
        yhprice: cartData.yhprice, //优惠金额
        psprice: cartData.psprice, //配送费
        street: addressData.street, //详细地址
        address: addressData.address, //门牌号
        username: addressData.name, //客户姓名
        mobile: addressData.mobile, //客户手机号
        bz: cartData.bz, //备注
        type: cartData.type, //支付类型
        zprice: this.data.zprice //商品价格 除去配送费的
      }
      if (this.data.id == -1) { //添加
        data.cartid = cartData.cart[0].id
        for (var i = 1; i < cartData.cart.length; i++) { //商品列表id
          data.cartid += ',' + cartData.cart[i].id
        }
        console.log(data)
        postOrderCreate(data).then(res => {
          if (res.state == 0) {
            let payData = {
              type: cartData.type, //支付类型
              price: cartData.price, //支付价格
              orderid: res.data //订单id
            }
            this.sumbitPay(payData)
          }
        })
      } else {
        data.id = cartData.id;
        postOrderUpdate(data).then(res => {
          if (res.state == 0) {
            let payData = {
              type: cartData.type, //支付类型
              price: cartData.price, //支付价格
              orderid: cartData.id //订单id
            }
            this.sumbitPay(payData)
          }
        })
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: '请填写收货地址!',
        duration: 2000
      })
    }
    console.log(this.data.cartData)
  },
  //支付
  sumbitPay(data) {
    var payType=data.type
    var orderId=data.orderid
    var that=this
    
    console.error("支付类型",payType)
    postPayJuhe(data).then(res => {
      if (res.state == 0) {
        console.log(res.data)
        
        if(payType==1){   //微信支付
          var payData = JSON.parse(res.data.payinfo)
          console.log(payData)
          console.error("微信支付")
          wx.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.package,
            signType: payData.signType,
            paySign: payData.paySign,
            success(res) {
              console.log(res)
              that.orderPrint(orderId)  //打印小票
              // that.test()   ////打印机打印
              wx.redirectTo({
                url: '../paySuccess/paySuccess',
              })
            },
            fail(res) {
              wx.showToast({
                title: '支付取消!',
                icon:"none",
              })
              // wx.reLaunch({
              //   url: '../we/we',
              // })
              // setTimeout(function(){

              // },1500)

            }
          })  
        }else{        //余额支付
          console.log("余额支付")
          this.orderPrint(orderId)    //打印小票
          //  that.test()       //打印机打印
          wx.redirectTo({
            url: '../paySuccess/paySuccess',
          })
        }


      } else {
        wx.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false,
          confirmColor: '#DF1A1A',
          success(res) {
            // wx.redirectTo({
            //   url: '../we/we',
            // })
          }
        })
      }
    })
  },
  //打印小票
  orderPrint(orderid) {
    let data = {
      orderid: orderid
    }
    posPrintMsg(data).then(res => {
      if (res.state == 0) {

      }
    })
  },
  //微信小程序https请求实例，根据自己的需求条件触发函数，推送订单打印
  test: function () {

    //USER和UKEY在飞鹅云（ http://admin.feieyun.com/ ）管理后台的个人中心可以查看
    var USER = "2575958295@qq.com";//必填，飞鹅云 http://admin.feieyun.com/ 管理后台注册的账号名
    var UKEY = "XKJuVYR9v57EyhBW";//必填，这个不是填打印机的key，是在飞鹅云后台注册账号后生成的UKEY

    var SN = '930519173';//必填，打印机编号,打印机必须要在管理后台先添加

    //以下URL参数不需要修改
    var HOST = "api.feieyun.cn";     //域名
    var PATH = "/Api/Open/";         //接口路径
    var STIME = new Date().getTime();//请求时间,当前时间的秒数
    var SIG = hex_sha1(USER + UKEY + STIME);//获取签名

    //标签说明：
    //单标签:
    //"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
    //"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
    //成对标签：
    //"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
    //<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT></RIGHT>"为右对齐
    //拼凑订单内容时可参考如下格式
    //根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

    var orderInfo;
    orderInfo = "<LOGO></LOGO>"
    orderInfo += '<CB>毕成中餐厅</CB><BR>';
    orderInfo += '名称　　　　　 单价  数量 金额<BR>';
    orderInfo += '--------------------------------<BR>';
    orderInfo += '饭　　　　　 　10.0   10  10.0<BR>';
    orderInfo += '炒饭　　　　　 10.0   10  10.0<BR>';
    orderInfo += '蛋炒饭　　　　 10.0   100 100.0<BR>';
    orderInfo += '西红柿鸡蛋炒饭西红柿鸡蛋炒饭西红柿鸡蛋炒饭 15.0   1   15.0<BR>';
    orderInfo += '备注：' + this.data.cartData.bz + '<BR>';
    orderInfo += '--------------------------------<BR>';
    orderInfo += '优惠金额：' + this.data.cartData.yhprice + '元<BR>';
    orderInfo += '配送费：' + this.data.cartData.psprice + '元<BR>';
    orderInfo += '实付：' + this.data.cartData.price + '元<BR>';
    orderInfo += '送货姓名：' + this.data.addressData.name + '<BR>';
    orderInfo += '送货地点：' + this.data.addressData.street + '-' + this.data.addressData.address + '<BR>';
    orderInfo += '联系电话：' + this.data.addressData.mobile + '<BR>';
    orderInfo += '订餐时间：' + STIME + '<BR>';
    // orderInfo += '<QR>http://www.dzist.com</QR>';//把二维码字符串用标签套上即可自动生成二维码

    //***接口返回值说明***
    //正确例子：{"msg":"ok","ret":0,"data":"123456789_20160823165104_1853029628","serverExecutedTime":6}
    //错误：{"msg":"错误信息.","ret":非零错误码,"data":null,"serverExecutedTime":5}
    // console.log(orderInfo);
    //打开注释可测试
    print_r(SN, orderInfo, 1);

    var hexcase = 0;
    var chrsz = 8;
    function hex_sha1(s) {
      return binb2hex(core_sha1(AlignSHA1(s)));
    }
    function core_sha1(blockArray) {
      var x = blockArray;
      var w = Array(80);
      var a = 1732584193;
      var b = -271733879;
      var c = -1732584194;
      var d = 271733878;
      var e = -1009589776;
      for (var i = 0; i < x.length; i += 16) {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;
        var olde = e;
        for (var j = 0; j < 80; j++) {
          if (j < 16)
            w[j] = x[i + j];
          else
            w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
          var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
          e = d;
          d = c;
          c = rol(b, 30);
          b = a;
          a = t;
        }
        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
        e = safe_add(e, olde);
      }
      return new Array(a, b, c, d, e);
    }

    function sha1_ft(t, b, c, d) {
      if (t < 20)
        return (b & c) | ((~b) & d);
      if (t < 40)
        return b ^ c ^ d;
      if (t < 60)
        return (b & c) | (b & d) | (c & d);
      return b ^ c ^ d;
    }

    function sha1_kt(t) {
      return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
    }

    function safe_add(x, y) {
      var lsw = (x & 0xFFFF) + (y & 0xFFFF);
      var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
      return (msw << 16) | (lsw & 0xFFFF);
    }

    function rol(num, cnt) {
      return (num << cnt) | (num >>> (32 - cnt));
    }

    function AlignSHA1(str) {
      var nblk = ((str.length + 8) >> 6) + 1,
        blks = new Array(nblk * 16);
      for (var i = 0; i < nblk * 16; i++)
        blks[i] = 0;
      for (i = 0; i < str.length; i++)
        blks[i >> 2] |= str.charCodeAt(i) << (24 - (i & 3) * 8);
      blks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);
      blks[nblk * 16 - 1] = str.length * 8;
      return blks;
    }

    function binb2hex(binarray) {
      var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
      var str = "";
      for (var i = 0; i < binarray.length * 4; i++) {
        str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) +
          hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
      }
      return str;
    }

    /*
    *  打印订单方法：Open_printMsg
    */
    function print_r(SN, orderInfo, TIMES) {
      wx.request({
        url: 'https://' + HOST + PATH,
        data: {
          user: USER,//账号
          stime: STIME,//当前时间的秒数，请求时间
          sig: SIG,//签名

          apiname: "Open_printMsg",//不需要修改
          sn: SN,//打印机编号
          content: orderInfo,//打印内容
          times: TIMES,//打印联数,默认为1
        },
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          console.log(res.data)
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})